package org.ocean.online.sys.inner;

import java.io.File;
import java.io.IOException;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.ocean.online.sys.DbGuard;
import org.ocean.online.utils.UserUtil;

import sun.org.mozilla.javascript.internal.NativeFunction;
import sun.org.mozilla.javascript.internal.NativeObject;
import sun.org.mozilla.javascript.internal.ScriptableObject;
import sun.org.mozilla.javascript.internal.json.JsonParser;

public class Sys {
	
	private DbGuard db;
	
	private IO io;

	ScriptEngine engine;
	
	public Sys(){
	}
	
	public Object require(String name){
		Req req = (Req) engine.getBindings(ScriptContext.ENGINE_SCOPE).get("req");
		String fullPath = UserUtil.getFullFilePath(req.httpServletRequest);
		File file = new File(fullPath);
		String requireFilePath = file.getParent()+File.separator+name;
		try {
			Object result = engine.eval(FileUtils.readFileToString(new File(requireFilePath)));
//			if(result.getClass().getName().equals("sun.org.mozilla.javascript.internal.InterpretedFunction")){
//				NativeFunction func = (NativeFunction)result;
//				return func;
//			}
			return result;
		} catch (ScriptException e) {
			throw new RuntimeException("执行文件["+name+"]失败: "+e.getMessage(),e);
		} catch (IOException e) {
			throw new RuntimeException("加载文件["+requireFilePath+"]失败");
		}
	}
	
	public ScriptEngine getEngine() {
		return engine;
	}

	public Object export(Object obj){
		return obj;
	}
	public void setEngine(ScriptEngine engine) {
		this.engine = engine;
	}

	public DbGuard getDb() {
		return db;
	}

	public void setDb(DbGuard db) {
		this.db = db;
	}

	public IO getIo() {
		return io;
	}

	public void setIo(IO io) {
		this.io = io;
	}
	
	public JSONObject newJSON(){
		return new JSONObject();
	}
	
	public JSONArray newJSONArray(){
		return new JSONArray();
	}
}
